require("jquery");
require('layout/util');
var $alert = require('libs/alert');
var $confirm = require('libs/confirm');
var $form = require('js-path/formValide.js');
var isModify = false;
var currentModifyName = '';
$(function () {
    /*$('#checkbox_list').on('change','input[type=radio]',function () {
        var $this = $(this);
        if($this.prop('checked')){
            $this.siblings().prop('checked',false);
        }
    });*/
    if(isModify){
        $("#channel_form").attr("action","api/v1/p/mms/logisticsChannel/update")
        channelFormValide();
    }else{
        $("#channel_form").attr("action","api/v1/p/mms/logisticsChannel/create")
        channelFormValide();
    }
    appendOption('api/v1/p/mms/internationalLogisticsProvider/query',{}
        ,$("#code"));
    comboboxInit('api/v1/p/crm/warehouse/query',{
            warehouseType:"DOME"}
        ,$("#fromWarehouseId"));
    comboboxInit('api/v1/p/crm/warehouse/query',{
            warehouseType:"DEST"}
        ,$("#toWarehouseId"));
    comboboxInit1('api/v1/p/mms/internationalLogisticsProvider/query',{}
        ,$("#providerId"));

    $("#productAddBack").on("click",function () {
        window.history.go(-1);
    });
    judge();
    $('#name').bind('keypress',function(event){
        if($('#logisticsName').val() == $('#name').val()){
            return;
        }
        if(event.keyCode == "13") {
            var data = {};
            data['name']=$('#name').val();
            data['code']=$('#logisticCode').val();
            var url ='';
            if($('#logisticsId').val()==''){
                url ='api/v1/p/mms/logistics/create';
            }else{
                url ='api/v1/p/mms/logistics/update';
                data['id']=$('#logisticsId').val();
            }
            opt(url,data,function (result) {
                if(result.code =='200'){
                    $('#nameMsg').html('');
                    $('#nameDiv').removeClass("has-error");
                    $('#codeDiv').removeClass("has-error");
                    $alert(result.message);
                    $('#logisticsId').val(result.data);
                    $('#logisticsName').val($('#name').val());
                    load(result.data);
                }else{
                    $('#nameDiv').addClass("has-error");
                    $('#codeDiv').addClass("has-error");
                    $alert(result.message);
                  //  $('#nameMsg').html("<p id='code-error' class='error'>"+result.message+"</p>");
                }
            })
        }

    });
    $('#myModal').on("show.bs.modal",function () {
        if($("#logisticsId").val()==''){
            $alert("请先创建物流产品!")
            return false;
        }else{
            $.ajax({
                url:"api/v1/p/crm/warehouse/query",
                type:'post',
                data:{
                    warehouseType:"DOME"
                },
                dataType:'json',
                success:function (result) {
                    $("#checkbox_list").html('');
                    var str='';
                    $.each(result.data,function (index,obj) {
                        str = str+"<input type='radio' name='rd' value='"+obj.warehouseId+"'><span>"+obj.warehouseName+"</span>";
                    })
                    $("#checkbox_list").append(str);
                    //如果是修改，则初始化数据
                    if(isModify){
                        //channelId
                        var modifyId = $("input[name=modifyId]").val();
                        $.ajax({
                            url:"api/v1/p/mms/logisticsChannel/detail",
                            type:'post',
                            data:{
                                id:modifyId
                            },
                            dataType:'json',
                            success:function (result) {
                                if(result.code=='200'){
                                    var data = result.data;
                                    $('#channel_form').attr('action','api/v1/p/mms/logisticsChannel/update')
                                    $("#channel_form input[name=channelName]").val(data.name);
                                    $("#channel_form input[name=channelCode]").val(data.channelCode);
                                    $("#channel_form select[name=fromWarehouseId]").val(data.fromWarehouseId);
                                    $("#channel_form select[name=toWarehouseId]").val(data.toWarehouseId);
                                    $("#channel_form select[name=providerId]").val(data.providerId);
                                    $("#providerName").text(data.providerName);
                                    $("#channel_form input[name=remark]").val(data.remark);
                                    $("#channel_form input[name=fastTimeliness]").val(data.fastTimeliness);
                                    $("#channel_form input[name=lastTimeliness]").val(data.lastTimeliness);
                                    if ($("#providerId").val() != '') {
                                        var data_obj = $("#providerId option:selected").attr("data_obj");
                                        serviceCategoryInit(JSON.parse(data_obj),$("#serviceCategory"));
                                        $("#channel_form select[name=serviceCategory]").val(data.serviceCategory);
                                    } else {
                                        $("#serviceCategory").html('');
                                    }
                                    var $checkbox = $("#checkbox_list input[type=radio]");
                                    $.each($checkbox,function (i,o) {
                                        var $this = $checkbox.eq(i);
                                        $.each(data.warehouses,function (j,p) {
                                            if($this.val()==p.warehouseId){
                                                $this.attr("checked","checked");
                                            }
                                        })
                                    });

                                }else{
                                    $alert(result.message);
                                }
                            },
                            error:function (e) {
                                console.error('接口获取失败');
                            }
                        })
                    }
                },
                error:function (e) {
                    console.error('接口获取失败');
                }
            })
        }
    });
    $('#myModal').on("hidden.bs.modal",function () {
        isModify = false;
        $('#myModal input').val('');
        $('#myModal select').val('');
        $('#myModal input[type=radio]').attr("checked",false);
        $("#providerName").text('');
    });
    //物流渠道改变事件
    $("#providerId").on("change",function () {
        var name = $("#providerId option:selected").attr("name");
        $("#providerName").text(name);
    });
    $(".modal-footer button:last").on("click",function () {
        $("#channel_form").submit();
    });
    $("#channelTable").on("click","a[name=delete]",function () {
        var id = $(this).parent().parent().children().eq(0).text();
        var $this = $(this).parent().parent();
        $confirm('确认删除该信息吗',function () {
            $.ajax({
                url:"api/v1/p/mms/logisticsChannel/delete",
                type:'post',
                data:{
                    id:id
                },
                dataType:'json',
                success:function (result) {
                    if(result.code=='200'){
                        $this.remove();
                        $alert("删除成功!");
                    }else{
                        $alert(result.message);
                    }
                },
                error:function (e) {
                    console.error('接口：获取失败');
                }
            })
        });
    });
    $("#channelTable").on("click","a[name=modify]",function () {
        isModify = true;
        $("#channel_form").attr("action","api/v1/p/mms/logisticsChannel/update")
        channelFormValide();
        var id = $(this).parent().parent().children().eq(0).text();
        $("#channel_form input[name=modifyId]").val(id);
        currentModifyName = $(this).parent().parent().children().eq(1).text();
        console.log("currentModifyName:"+currentModifyName);
        $("#myModal").modal('show');
    });
    $("#providerId").on('change', function () {
        if ($(this).val() != '') {
            var data = $("#providerId option:selected").attr("data_obj");
            serviceCategoryInit(JSON.parse(data),$("#serviceCategory"));
        } else {
            $("#serviceCategory").html('');
        }
    });
});
//表单验证
function channelFormValide() {
    $form({selector:'#channel_form'},{
        channelName:{required:true},channelCode:{required:true},fromWarehouseId:{required:true},
        toWarehouseId:{required:true},providerId:{required:true},serviceCategory:{required:true},
        fastTimeliness:{required:true} ,lastTimeliness:{required:true}
    },{channelName:{required:'海外仓不能为空'},fromWarehouseId:{required:'电商平台不能为空'},
        toWarehouseId:{required:'姓不能为空'},providerId:{required:'名不能为空'},serviceCategory :{required:'服务种类不能为空'},
        fastTimeliness :{required:'时效不能为空'} ,lastTimeliness :{required:'时效不能为空'}
    },function () {
        var flag = warehousesValid($("#channelTable tbody"));
        if(!flag){
            return false;
        }
        var formObj = $('#channel_form').serializeObject();
        formObj["name"] = formObj.channelName;
        formObj["channelCode"] = formObj.channelCode;
        delete formObj.channelName;
        var warehouses = [];
        var $checked = $("#checkbox_list input:checked");
        $.each($checked,function (i,o) {
            var id = {};
            id["id"] = $checked.eq(i).val();
            warehouses.push(id);
        });
        formObj["warehouses"] = warehouses;
        var logisticsId = $("#logisticsId").val();
        var logisticsCode = $("#logisticCode").val();
        if(logisticsId==''){
            $alert("请先创建物流产品!")
        }else{
            formObj["logisticsId"] = logisticsId;
            formObj["logisticsCode"] = logisticsCode;
        }
        var fastTimeliness = parseInt($("#fastTimeliness").val());
        var lastTimeliness = parseInt($("#lastTimeliness").val());
        if (isNaN(fastTimeliness) || isNaN(lastTimeliness) ){
            $alert("时效字段应该为数字格式!")
            return ;
        }
        if (fastTimeliness >= lastTimeliness){
            $alert("最大时效应大于最小时效!")
            return ;
        }

        var channelId = formObj["modifyId"];
        if(isModify){
            formObj["id"] = channelId;
        }
        delete formObj["modifyId"];
        if(isModify){
            modifyAjax(formObj);
            return false;
        }
        return formObj;
    },function (result) {
        if(result.code == 200){
            var logisticsId = $("#logisticsId").val();
            console.log("新建完成")
            load(logisticsId);
            $("#myModal").modal("hide");
        }else{
            console.log("新建失败")
            $alert(result.message);
        }
    });
}
function modifyAjax(data){
    $.ajax({
        url:"api/v1/p/mms/logisticsChannel/update",
        type:'post',
        data:JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType:'json',
        success:function (result) {
            if(result.code=='200'){
                var logisticsId = $("#logisticsId").val();
                console.log("新建完成")
                load(logisticsId);
                $("#myModal").modal("hide");
            }else{
                $alert(result.message);
            }
        },
        error:function (e) {
            console.error('接口：获取失败');
        }
    })
}
function warehousesValid($tbody) {
    var l = $("#checkbox_list input:checked").length;
    var flag1 = true;
    var flag2 = true;
    if(l<=0){
        $("#checkbox_list").next("div").empty();
        $("#checkbox_list").next("div").append('<span id="warehouses-error" class="error-info" style="color: red">请选择集货仓</span>')
        flag1 = false;
    }else{
        $("#checkbox_list").next("div").empty();
        flag1 = true;
    }
    var $exist = $tbody.children("tr");
    //判断该物流线路是否存在
    $.each($exist,function (i,o) {
        var $this = $exist.eq(i).children("td:eq(1)");
        if($('input[name=channelName]').val()==$this.text()){
            if($('input[name=channelName]').val()==currentModifyName){
                $('input[name=channelName]').parent().next("div").empty();
                flag2 = true;
            }else{
                $('input[name=channelName]').parent().next("div").empty();
                $('input[name=channelName]').parent().next("div").append('<span id="warehouses-error" class="error-info" style="color: red">该物流线路已经存在</span>')
                $alert("该物流线路已经存在");
                flag2 = false;
                return false
            }
        }else{
            $('input[name=channelName]').parent().next("div").empty();
            flag2 = true;
        }
    });
    return flag1&&flag2;
}
//opt 操作 callback回调函数
function opt(url,data,callback) {
    $.ajax({
        url:url,
        type:'post',
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(data),
        dataType:'json',
        success:function (result) {
            callback(result);
        },
        error:function (e) {
            console.error('接口：'+url+'获取失败');
        }
    })
}

//添加参数
function appendOption(url,data,$select) {
    $.ajax({
        url:url,
        type:'post',
        data:data,
        dataType:'json',
        success:function (result) {
            if(result.code==200){
                $select.combobox({
                    data:result.data,
                    valueField:'id',
                    textField:'code'
                });
            }else{
                console.error(result.message);
            }
        },
        error:function (e) {
            console.log('接口错误');
        }
    })
}
//添加参数
function appendOption1(url,data,$select) {
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        dataType: 'json',
        success: function (result) {
            if (result.code == 200) {
                console.log(111);
                $select.combobox({
                    data: result.data,
                    valueField: 'warehouseId',
                    textField: 'warehouseName'
                });
            } else {
                console.error(result.message);
            }
        },
        error: function (e) {
            console.log('接口错误');
        }
    })
}
function comboboxInit(url,data,$select) {
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        dataType: 'json',
        success: function (result) {
            if (result.code == 200) {
                var list = result.data;
                $select.html('');
                $select.append("<option value=''>请选择</option>")
                $.each(list,function (i,o) {
                    $select.append("<option value='"+o.warehouseId+"'>"+o.warehouseName+"</option>")
                })
            } else {
                console.error(result.message);
            }
        },
        error: function (e) {
            console.log('接口错误');
        }
    })
}
function comboboxInit1(url,data,$select) {
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        dataType: 'json',
        success: function (result) {
            if (result.code == 200) {
                var list = result.data;
                $select.html('');
                $select.append("<option value=''>请选择</option>")
                $.each(list,function (i,o) {
                    var data = JSON.stringify(o.serviceCategoryVOS);
                    $select.append("<option name='"+o.name+"' value='"+o.id+"' data_obj='"+data+"'>"+o.code+"</option>")
                })
            } else {
                console.error(result.message);
            }
        },
        error: function (e) {
            console.log('接口错误');
        }
    })
}

//judge判断新增或更新
function judge() {
    var url =window.location.href;
    if(url.indexOf("id=")>0){
        $('span.name:first').html('物流产品更新');
        var id = $.getUrlParam('id');
        load(id);
    }
}

//load
function load(id) {
    $.ajax({
        url:'api/v1/p/mms/logistics/detail',
        type:'post',
        data:{
            id:id
        },
        dataType:'json',
        success:function (result) {
            if (result.code == 200){
                $("#channelTable tbody").html('');
                var html = '';
                $.each(result.data.channels,function (index,obj) {
                    html +="<tr> <td style='display: none'>"+obj.id+"</td><td>"+obj.name+"</td><td>"+obj.channelCode+"</td> <td>"+obj.fromWarehouseName+"</td> <td>"+obj.toWarehouseName+"</td> <td>";
                    $.each(obj.warehouses,function (indexC,objC) {
                        html+=objC.warehouseName+',';
                    });
                    html+="</td> <td><a href='javascript:;' name='delete'>删除</a><a href='javascript:;' name='modify'>修改</a> </td> </tr>";
                });
                $("#channelTable tbody").append(html);
                $('#logisticCode').val(result.data.code);
                $('#name').val(result.data.name);
                $('#logisticsId').val(result.data.id);
            }else{
                $alert(result.message);
            }
        },
        error:function (e) {
            console.error('api/v1/p/mms/logistics/detail 接口调用失败 ' )
        }
    })
}

function serviceCategoryInit(data,$select){
    var list = data;
    $select.html('');
    $select.append("<option value=''>请选择</option>")
    $.each(list,function (i,o) {
        $select.append("<option name='"+o.code+"' value='"+o.code+"'>"+o.name+"</option>");
    })
}